import plugin from '../../lib/plugins/plugin.js'
import { segment } from 'oicq'
import fetch from "node-fetch";
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const blacklist = []
let CD = {};// 命令CD
let isR18 = true;//群聊R18默认值
let isR18s = true;//私聊R18默认值
let interval= 10000;//连发模式的间隔时间，默认为10秒，由于图片质量不同导致发送时间不同，实际间隔可能有误差
let num = 3; //默认连发数量为3
let timeout = 10000
export class webPreview extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '截图预览网页内容',
            /** 功能描述 */
            dsc: '群里发送网页地址，截图预览网页内容',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 1006,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^(?:(http|https):\/\/)?((?:[\\w-]+\\.)+[a-z0-9]+)((?:\/[^\/?#]*)+)?(\\?[^#]+)?(#.+)?$',
                    /** 执行方法 */
                    fnc: 'webPreview'
                },
                {
                    reg: '^搜索.*$',
                    fnc: 'acgs'
                }
            ]
     
        })
    }

    /**
     * 
     * @param e oicq传递的事件参数e
	 
	 
	 
     */
	 
	 async acgs(e) {
        if (e.isGroup) { //群聊
            for (let i = 0; i < blacklist.length; i++) {
                if (e.group.group_id == blacklist[i]) {
                    e.reply("本群不可以色色！");
                    return true;
                }
            }
            if (CD[e.user_id] && !e.isMaster) {
                e.reply("每10秒只能冲一次哦！");//更改完冷却时间记得更改这里的时间.
                return true;
            }
            CD[e.user_id] = true;
            CD[e.user_id] = setTimeout(() => {
                if (CD[e.user_id]) {
                    delete CD[e.user_id];
                }
            }, 10000);//这里是冷却时间，单位毫秒.
            e.reply(`派蒙正在搜图，等一下哦`);
            let keyword = e.msg.replace("#", "");
            keyword = keyword.replace("搜索", "");
            let url = '';
            if (!isR18) {
                url = `https://api.lolicon.app/setu/v2?tag=${keyword}&proxy=i.pixiv.re&r18=0`;//setu接口地址，把这里的18=0改成18=1可以发送r18图片，18=2则为混合图片.
            } else {
                url = `https://api.lolicon.app/setu/v2?tag=${keyword}&proxy=i.pixiv.re&r18=0`;
            }
            const response = await fetch(url); //调用接口获取数据
            let res = await response.json(); //结果json字符串转对象
            let imgurl = res.data[0].urls.original;
            if (res.data.length == 0) {
                e.reply("暂时没有搜到哦！换个关键词试试吧！");
                return true;
            }
            let TagNumber = res.data[0].tags.length;
            let Atags;
            let Btags;
            let qwq = 0;
            while (TagNumber--) {
                Atags = res.data[0].tags[TagNumber];
                if (qwq == 0) {
                    Btags = "";
                }
                Btags = Btags + " " + Atags;
                qwq++;
            }
            let msg;
            let pid = res.data[0].pid;
            //最后回复消息
			
			
            msg = [
           
                res.data[0].urls.original,
            ];
			
            //发送消息
			
			
			
           
			
			
			 const puppeteer = require('puppeteer');

        const browser = await puppeteer.launch({
            headless: true,
            args: [
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--disable-setuid-sandbox',
                '--no-first-run',
                '--no-sandbox',
                '--no-zygote',
                '--single-process'
              ]
        });
        const page = await browser.newPage();
        await page.goto(res.data[0].urls.original);
        await page.setViewport({
            width: 1920,
            height: 1080
        });
    
        let msgRes = await e.reply(segment.image(await page.screenshot({
            fullPage: true
        })))
		
		let timeout = 30000;
		e.reply("给你30秒的时间赶快解决。别让我再看到你！")
			
			
			
			
            if (timeout != 0 && msgRes && msgRes.message_id) {
                let target = e.group;
                setTimeout(() => {
                    target.recallMsg(msgRes.message_id);
                }, timeout);
            }
            return true; //返回true 阻挡消息不再往下
        } else {  //私聊
            if (CD[e.user_id] && !e.isMaster) {
                e.reply("每1分钟只能冲一次哦！");//更改完冷却时间记得更改这里的时间.
                return true;
            }
            CD[e.user_id] = true;
            CD[e.user_id] = setTimeout(() => {
                if (CD[e.user_id]) {
                    delete CD[e.user_id];
                }
            }, 60000);//这里是冷却时间，单位毫秒.
            e.reply(`正在搜图...`);
            let keyword = e.msg.replace("#", "");
            keyword = keyword.replace("搜索", "");
            let url = '';
            if (!isR18s) {
                url = `https://api.lolicon.app/setu/v2?tag=${keyword}&proxy=i.pixiv.re&r18=0`;//setu接口地址，把这里的18=0改成18=1可以发送r18图片，18=2则为混合图片.
            } else {
                url = `https://api.lolicon.app/setu/v2?tag=${keyword}&proxy=i.pixiv.re&r18=0`;
            }
            const response = await fetch(url); //调用接口获取数据
            let res = await response.json(); //结果json字符串转对象
            let imgurl = res.data[0].urls.original;
            if (res.data.length == 0) {
                e.reply("暂时没有搜到哦！换个关键词试试吧！");
                return true;
            }
            let TagNumber = res.data[0].tags.length;
            let Atags;
            let Btags;
            let qwq = 0;
            while (TagNumber--) {
                Atags = res.data[0].tags[TagNumber];
                if (qwq == 0) {
                    Btags = "";
                }
                Btags = Btags + " " + Atags;
                qwq++;
            }
            let msg;
            let pid = res.data[0].pid;
            //最后回复消息
            msg = [
                "标题：",
                res.data[0].title,
                "\n作者：",
                res.data[0].author,
                "\n关键词：",
                Btags,
                segment.image(res.data[0].urls.original),
            ];
            //发送消息
           
            return true; //返回true 阻挡消息不再往下
        }
    }

	 
    async webPreview(e) {

        const puppeteer = require('puppeteer');

        const browser = await puppeteer.launch({
            headless: true,
            args: [
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--disable-setuid-sandbox',
                '--no-first-run',
                '--no-sandbox',
                '--no-zygote',
                '--single-process'
              ]
        });
        const page = await browser.newPage();
        await page.goto(e.msg);
        await page.setViewport({
            width: 1920,
            height: 1080
        });
    
        let msgRes = await e.reply(segment.image(await page.screenshot({
            fullPage: true
        })))
		
		let timeout = 30000;
		e.reply("给你30秒的时间赶快解决。别让我再看到你！")
    
  //发送消息
  console.log(timeout,msgRes,msgRes.message_id)
  if (timeout!=0 && msgRes && msgRes.message_id){
    let target = null;
	console.log("ch")
    if (e.isGroup) {
      target = e.group;//是否为群聊
    }else{
      target = e.friend;//是否为好友
    }
    if (target != null){
		
      setTimeout(() => {
        target.recallMsg(msgRes.message_id);
      }, timeout);
    }
  } 
    
	
	
	
	
	
	
	
	
	
	
        await browser.close();
    }
	
	
	
}
